package com.ljh.blog.common.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author: Themberfue
 * @date: 2025/4/9 22:00
 * @description:
 */
public class SecurityUtils {
    /**
     * 加密
     * @param password 密码
     * @return 盐值 + md5(盐值+密码)
     */
    public static String encrypt(String password) {
        String salt = UUID.randomUUID().toString().replace("-", "");
        String encryptRes = DigestUtils.md5DigestAsHex((salt + password).getBytes(StandardCharsets.UTF_8));
        return salt + encryptRes;
    }

    /**
     * 验证
     * @param password 密码
     * @return 验证是否成功
     */
    public static boolean verify(String password, String sqlPassword) {
        if (!StringUtils.hasLength(password) || !StringUtils.hasLength(sqlPassword)) {
            return false;
        }
        String salt = sqlPassword.substring(0, 32);
        String encryptRes = DigestUtils.md5DigestAsHex((salt + password).getBytes(StandardCharsets.UTF_8));
        return sqlPassword.equals(salt + encryptRes);
    }
}
